package main

import (
	"elegantGo/chapter03/oo"
	"elegantGo/chapter03/pkg/validate"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"net/http"
)

func main() {

	validate.RegisterValidation("sort", func(fl validator.FieldLevel) bool {
		var sort oo.Sort
		return sort.IsValid(fl.Field().String())
	})

	validate.RegisterValidation("order", func(fl validator.FieldLevel) bool {
		var sort oo.Order
		return sort.IsValid(fl.Field().String())
	})

	validate.RegisterValidation("offset", func(fl validator.FieldLevel) bool {
		var offset oo.Offset
		return offset.IsValid(fl.Field().Int())
	})

	validate.RegisterValidation("limit", func(fl validator.FieldLevel) bool {
		var limit oo.Limit
		return limit.IsValid(fl.Field().Int())
	})

	validate.RegisterValidation("level", func(fl validator.FieldLevel) bool {
		var level oo.Level
		level.SetValue64(fl.Field().Int())
		return level.IsValid()
	})

	validate.RegisterValidation("isdefaultfield", func(fl validator.FieldLevel) bool {
		return validate.IsDefaultField(fl)
	})

	srv := gin.Default()

	srv.POST("/users", func(c *gin.Context) {

		type Users struct {
			Sort   *oo.Sort   `binding:"omitempty,sort"`
			Order  *oo.Order  `binding:"omitempty,order"`
			Offset *oo.Offset `binding:"omitempty,offset"`
			Limit  *oo.Limit  `binding:"omitempty,limit"`

			Level  *int  `binding:"omitempty,level"`
			Levels []int `binding:"omitempty,dive,level"`

			Point      oo.IntRange
			Balance    oo.FloatRange
			CreateTime oo.TimeRange
		}

		req := new(Users)
		if err := c.ShouldBind(req); err != nil {
			c.JSON(http.StatusOK, err.Error())
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"Sort":       req.Sort.OrDefault(),
			"Order":      req.Order.OrDefault(),
			"Offset":     req.Offset.OrDefault(),
			"Limit":      req.Limit.OrDefault(),
			"Level":      req.Level,
			"Levels":     req.Levels,
			"Point":      req.Point,
			"Balance":    req.Balance,
			"CreateTime": req.CreateTime,
		})
	})

	srv.Run(":80")
}
